﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TradingServer.Core.Entities
{
	public class Briefcase
	{
		public Briefcase(Account acc)
		{
			Account = acc;
		}

		public Account Account { get; private set; }
		public IEnumerable<BriefcaseItem> Items
		{
			get { lock (_briefcaseItemsLock) return _items; }
		}

		public void Add(IEnumerable<Trade> trades)
		{
			lock (_briefcaseItemsLock)
			{
				foreach (Trade trade in trades)
				{
					var currentTrade = trade;
					var item = _items.SingleOrDefault(p => p.Security.Equals(currentTrade.Security));
					if (item == null)
					{
						_items.Add(new BriefcaseItem { Briefcase = this, Security = currentTrade.Security, Volume = currentTrade.Volume, Price = currentTrade.Price });
						continue;
					}

					decimal avgPrice = (item.TotalPrice + currentTrade.TotalPrice) / (item.Volume + currentTrade.Volume);
					item.Price = avgPrice;
					item.Volume += currentTrade.Volume;
				}
			}
		}

		#region Private members

		private readonly object _briefcaseItemsLock = new object();
		private readonly List<BriefcaseItem> _items = new List<BriefcaseItem>();

		#endregion

	}
}
